#!/bin/bash

# 显示帮助信息
show_help() {
  echo "用法: $0 [选项]"
  echo "选项:"
  echo "  -m, --mode MODE       部署模式 (local 或 server)"
  echo "  -p, --port PORT       服务端口 (默认: 5000)"
  echo "  -i, --ip IP           服务器公网IP (server模式必需)"
  echo "  -j, --jwt JWT_SECRET  JWT密钥 (可选)"
  echo "  -h, --help            显示帮助信息"
  echo ""
  echo "示例:"
  echo "  本地部署: $0 -m local -p 5000"
  echo "  服务器部署: $0 -m server -p 5000 -i your_server_ip"
}

# 获取公网IP
get_public_ip() {
  if [ -z "$PUBLIC_IP" ]; then
    echo "正在获取公网IP..."
    PUBLIC_IP=$(curl -s https://api.ipify.org || curl -s https://ifconfig.me)
    if [ -z "$PUBLIC_IP" ]; then
      echo "无法获取公网IP，请手动指定"
      exit 1
    fi
  fi
}

# 生成JWT密钥
generate_jwt_secret() {
  if [ -z "$JWT_SECRET" ]; then
    JWT_SECRET=$(openssl rand -base64 32)
  fi
}

# 解析命令行参数
parse_args() {
  while [[ $# -gt 0 ]]; do
    case $1 in
      -m|--mode)
        DEPLOY_MODE="$2"
        shift 2
        ;;
      -p|--port)
        BACKEND_PORT="$2"
        shift 2
        ;;
      -i|--ip)
        PUBLIC_IP="$2"
        shift 2
        ;;
      -j|--jwt)
        JWT_SECRET="$2"
        shift 2
        ;;
      -h|--help)
        show_help
        exit 0
        ;;
      *)
        echo "未知选项: $1"
        show_help
        exit 1
        ;;
    esac
  done
}

# 检查必要参数
check_requirements() {
  if [ -z "$DEPLOY_MODE" ]; then
    echo "错误: 必须指定部署模式 (-m 或 --mode)"
    show_help
    exit 1
  fi

  if [ "$DEPLOY_MODE" = "server" ] && [ -z "$PUBLIC_IP" ]; then
    echo "错误: 服务器模式必须指定公网IP (-i 或 --ip)"
    show_help
    exit 1
  fi
}

# 设置默认值
DEPLOY_MODE=""
BACKEND_PORT=5000
PUBLIC_IP=""
JWT_SECRET=""

# 解析参数
parse_args "$@"

# 检查必要参数
check_requirements

# 生成JWT密钥
generate_jwt_secret

# 创建必要的目录
mkdir -p uploads/thumbnails
mkdir -p uploads/originals

# 根据部署模式设置环境变量
if [ "$DEPLOY_MODE" = "local" ]; then
  # 本地部署模式
  echo "使用本地部署模式..."
  
  # 创建本地环境变量文件
  cat > .env << EOF
BACKEND_PORT=${BACKEND_PORT}
JWT_SECRET=${JWT_SECRET}
MONGO_URI=mongodb://localhost:27017/photo_album
REACT_APP_API_URL=http://localhost:${BACKEND_PORT}
EOF

  # 检查是否安装了必要的软件
  if ! command -v node &> /dev/null; then
    echo "错误: 未安装 Node.js"
    exit 1
  fi

  if ! command -v npm &> /dev/null; then
    echo "错误: 未安装 npm"
    exit 1
  fi

  # if ! command -v mongod &> /dev/null; then
  #   echo "错误: 未安装 MongoDB"
  #   exit 1
  # fi

  # 安装依赖
  echo "安装后端依赖..."
  cd backend
  npm install
  cd ..

  echo "安装前端依赖..."
  cd frontend
  npm install
  cd ..

  # 构建前端
  echo "构建前端..."
  cd frontend
  npm run build
  cd ..

  # 创建后端public目录并复制前端构建文件
  echo "复制前端构建文件到后端..."
  mkdir -p backend/public
  cp -r frontend/build/* backend/public/

  # 启动服务
  echo "启动服务..."
  echo "1. 确保 MongoDB 服务已启动"
  echo "2. 在新的终端窗口中运行: cd backend && npm start"
  echo "3. 访问: http://localhost:${BACKEND_PORT}"

else
  # 服务器部署模式
  echo "使用服务器部署模式..."
  get_public_ip

  # 创建服务器环境变量文件
  cat > .env << EOF
BACKEND_PORT=${BACKEND_PORT}
JWT_SECRET=${JWT_SECRET}
PUBLIC_IP=${PUBLIC_IP}
MONGO_PORT=27017
REACT_APP_API_URL=http://${PUBLIC_IP}:${BACKEND_PORT}
EOF

  # 检查Docker是否安装
  if ! command -v docker &> /dev/null; then
    echo "错误: 未安装 Docker"
    exit 1
  fi

  if ! command -v docker-compose &> /dev/null; then
    echo "错误: 未安装 Docker Compose"
    exit 1
  fi

  # 创建docker-compose.yml
  cat > docker-compose.yml << EOF
version: '3.8'

services:
  app:
    build:
      context: .
      args:
        - PUBLIC_IP=${PUBLIC_IP}
        - BACKEND_PORT=${BACKEND_PORT}
    ports:
      - "${BACKEND_PORT}:${BACKEND_PORT}"
    environment:
      - NODE_ENV=production
      - JWT_SECRET=${JWT_SECRET}
      - MONGO_URI=mongodb://mongodb:27017/photo_album
      - REACT_APP_API_URL=http://${PUBLIC_IP}:${BACKEND_PORT}
    volumes:
      - ./uploads:/app/uploads
    depends_on:
      - mongodb
    restart: unless-stopped

  mongodb:
    image: mongo:latest
    ports:
      - "27017:27017"
    volumes:
      - mongodb_data:/data/db
    restart: unless-stopped

volumes:
  mongodb_data:
EOF

  # 构建和启动容器
  echo "构建和启动容器..."
  docker-compose up -d --build

  # 等待服务启动
  echo "等待服务启动..."
  sleep 10

  # 检查服务状态
  if docker-compose ps | grep -q "Up"; then
    echo "服务已成功启动！"
    echo "访问地址: http://${PUBLIC_IP}:${BACKEND_PORT}"
  else
    echo "服务启动失败，请检查日志"
    docker-compose logs
  fi
fi

# 生成部署说明
cat > DEPLOY.md << EOF
# 部署说明

## 部署信息
- 部署模式: ${DEPLOY_MODE}
- 服务端口: ${BACKEND_PORT}
- 公网IP: ${PUBLIC_IP:-localhost}
- JWT密钥: ${JWT_SECRET}

## 环境变量配置
\`\`\`
BACKEND_PORT=${BACKEND_PORT}
JWT_SECRET=${JWT_SECRET}
${PUBLIC_IP:+PUBLIC_IP=${PUBLIC_IP}}
MONGO_URI=mongodb://${DEPLOY_MODE:-localhost}:27017/photo_album
REACT_APP_API_URL=http://${PUBLIC_IP:-localhost}:${BACKEND_PORT}
\`\`\`

## 访问地址
- 前端: http://${PUBLIC_IP:-localhost}:${BACKEND_PORT}
- 后端API: http://${PUBLIC_IP:-localhost}:${BACKEND_PORT}/api

## 重要说明
1. 请确保服务器防火墙已开放 ${BACKEND_PORT} 端口
2. 建议使用 HTTPS 保护数据传输
3. 定期备份 uploads 目录中的文件
4. 请妥善保管 JWT_SECRET
5. 如需修改配置，请更新 .env 文件后重启服务
EOF

echo "部署完成！详细说明请查看 DEPLOY.md" 